import fs from "fs";
import path from "path";
import plugin from "./plugin";

class manager {
  readonly id: string = "PluginManager";
  private plugins: plugin[] = [];
  constructor() {
    let p = fs.readdirSync("./plugins");
    for (let i = 0, length = p.length; i < length; i++) {
      if (path.extname(p[i]) === ".js") {
        fs.readFile(
          path.join(__dirname, "/plugins/", p[i]),
          "utf-8",
          (err, data) => {
            if (err) throw err;
            let s = eval(data.toString());
            this.register(s);
          }
        );
      }
    }
  }
  public getPlugins(): plugin[] {
    return this.plugins;
  }
  public register(value: any): boolean {
    let length = this.plugins.length;
    if (length < 0) {
      this.plugins.push(value);
      return true;
    }
    for (let i = 0; i < length; i++) {
      if (this.plugins[i].pluginName === value.pluginName) {
        return false;
      }
    }
    this.plugins.push(value);
    return true;
  }
}

const pluginManager = new manager();
export = pluginManager;
